package com.stn.zjx.givingtreasure.utils;




import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.stn.zjx.givingtreasure.BuildConfig;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.net.BaseApi;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class ToolsUtils {



    //校验密码，必须是字母加数字6-20个字符
    public static boolean checkUserPassword(String userPassword) {
        String regex = "^^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(userPassword);
        return m.matches();
    }

    //校验昵称，必须是中文，字母,数字
    public static boolean checkName(String  name){
        String regex = "[0-9A-Za-z\\u4e00-\\u9fa5]{2,10}";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(name);
        return m.matches();
    }

    /**
     * 格式化单位
     *
     * @param size size
     * @return size
     */
    public static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }


    //得到服务器公共参数
    public static String getCommonParams(){
        try {
            return    Base64Utils.encode(new EncrypAES(BaseApi.COMMON_AES_KEY).Encrytor(BaseApi.Client_CommonParams));
        }  catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    //参数加密，aes,base64
    public static String getEncryptionParams(String data){
        try {
          return   Base64Utils.encode(new EncrypAES(BaseApi.MD5_AES_KEY).Encrytor(data));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }



    //获取IP
    public static String getNetIp() {
        String ip = "";
        InputStream inStream = null;
        try {
            URL infoUrl = new URL("http://1212.ip138.com/ic.asp");
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "gb2312"));
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                    //builder.append(line).append("\n");
                }
                inStream.close();
                int start = builder.indexOf("[");
                int end = builder.indexOf("]");
                ip = builder.substring(start + 1, end);
                return ip;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    //返回字符串时间
    public static  String getDateBeforeAfter(long datetime){
        StringBuffer sb=new StringBuffer();
        long time=System.currentTimeMillis()-(datetime);
        long mill= (long) Math.ceil(time/1000.0f);
        long min= (long) Math.ceil(time/1000/60.0f);
        long  hour= (long) Math.ceil(time/1000/60/60.0f);
        long  day= (long) Math.ceil(time/1000/60/60/24.0f);
        long month=(long) Math.ceil(time/1000/60/60/24/30.0f);
        if(month-1>0){
            if(month>12){
               // sb.append("很久很久");
            }else if(month==12){
               // sb.append("1年");
            }else{
               // sb.append(month+"个月");
            }
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return  simpleDateFormat.format(new Date(datetime));
        }else if(day-1>0){
            if(day==30){
               // sb.append("1个月");
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("MM-dd HH:mm");
              return  simpleDateFormat.format(new Date(datetime));
            }else{
              //  sb.append(day + "天");
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("MM-dd HH:mm");
                return  simpleDateFormat.format(new Date(datetime));
            }

        }else if(hour-1>0){
            if(hour>=24){
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("MM-dd HH:mm");
                return  simpleDateFormat.format(new Date(datetime));
              //  sb.append("1天");
            }else{
                sb.append(hour+"小时");
            }
        }else if(min-1>0){
            if(min==60){
                sb.append(hour+"1小时");
            }else{
                sb.append(min+"分钟");
            }
        }else if(mill-1>0){
            if (mill == 60) {
                sb.append("1分钟");
            } else {
                sb.append(mill+"秒");
            }
        }else{
            sb.append("刚刚");
        }
        if(!sb.toString().equals("刚刚")){
            sb.append("前");
        }

        return sb.toString();
    }

    //返回字符串时间
    public static  String getDate(long datetime,String formate){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat(formate);
            return  simpleDateFormat.format(new Date(datetime));
    }



    public static byte[] readBytesFromFile(String filePath) {

        FileInputStream fileInputStream = null;
        byte[] bytesArray = null;

        try {

            File file = new File(filePath);
            bytesArray = new byte[(int) file.length()];

            //read file into bytes[]
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytesArray);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return bytesArray;

    }


    public static String getYear(Date date){
        //获取默认选中的日期的年月日星期的值，并赋值
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(date);//设置当前日期
        String getyearStr = calendar.get(Calendar.YEAR)+"";//获取年份
        int getmonth = calendar.get(Calendar.MONTH) + 1;//获取月份
        String monthStr = getmonth < 10 ? "0" + getmonth : getmonth + "";
        int day = calendar.get(Calendar.DATE);//获取日
        String getdayStr = day < 10 ? "0" + day : day + "";
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        String weekStr = "";
        return getyearStr;
    }
    public static String getMonth(Date date){
        //获取默认选中的日期的年月日星期的值，并赋值
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(date);//设置当前日期
        String getyearStr = calendar.get(Calendar.YEAR)+"";//获取年份
        int getmonth = calendar.get(Calendar.MONTH) + 1;//获取月份
        String monthStr = getmonth < 10 ? "0" + getmonth : getmonth + "";
        int day = calendar.get(Calendar.DATE);//获取日
        String getdayStr = day < 10 ? "0" + day : day + "";
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        String weekStr = "";
        return monthStr;
    }
    public static String getDay(Date date){
        //获取默认选中的日期的年月日星期的值，并赋值
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(date);//设置当前日期
        String getyearStr = calendar.get(Calendar.YEAR)+"";//获取年份
        int getmonth = calendar.get(Calendar.MONTH) + 1;//获取月份
        String monthStr = getmonth < 10 ? "0" + getmonth : getmonth + "";
        int day = calendar.get(Calendar.DATE);//获取日
        String getdayStr = day < 10 ? "0" + day : day + "";
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        String weekStr = "";
        return getdayStr;
    }
    public static String getWeek(Date date){
        //获取默认选中的日期的年月日星期的值，并赋值
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(date);//设置当前日期
        String getyearStr = calendar.get(Calendar.YEAR)+"";//获取年份
        int getmonth = calendar.get(Calendar.MONTH) + 1;//获取月份
        String monthStr = getmonth < 10 ? "0" + getmonth : getmonth + "";
        int day = calendar.get(Calendar.DATE);//获取日
        String getdayStr = day < 10 ? "0" + day : day + "";
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        String weekStr = "";
        switch (week) {
            case 1:
                weekStr = "周日";
                break;
            case 2:
                weekStr = "周一";
                break;
            case 3:
                weekStr = "周二";
                break;
            case 4:
                weekStr = "周三";
                break;
            case 5:
                weekStr = "周四";
                break;
            case 6:
                weekStr = "周五";
                break;
            case 7:
                weekStr = "周六";
                break;
            default:
                break;
        }
        return weekStr;
    }

    public static Bitmap comp(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
    }
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while ( baos.toByteArray().length / 1024>100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    public static void install(Context context,File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT>=24) {//判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(context, "com.stn.zjx.givingtreasure.fileprovider", file);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
            context.startActivity(install);
        } else{
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
            context.startActivity(install);
        }
        context.startActivity(intent);
    }

    /*
    * 将布局转化为bitmap
这里传入的是你要截的布局的根View
    * */
    public static Bitmap getBitmapByView(View headerView) {
        int h = headerView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(headerView.getWidth(), h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        headerView.draw(canvas);
        return bitmap;
    }

    public static void shareImage(Context context,File share){
                       Intent shareIntent = new Intent();
               if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                   shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                   Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", share);
                   shareIntent.setAction(Intent.ACTION_SEND);
                   shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
                   shareIntent.setType("image/*");
                  context. startActivity(Intent.createChooser(shareIntent, "分享图片"));
               } else {
                   shareIntent.setAction(Intent.ACTION_SEND);
                   shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(share));
                   shareIntent.setType("image/*");
                   context. startActivity(Intent.createChooser(shareIntent, "分享图片"));
               }
    }
    //跳转到应用信息
    public static void goSettingInfo(Context context){

        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName",context.getPackageName());
        }
        context.startActivity(localIntent);

    }
   //返回距离
    public static String getM(double m){

        if(m<50){
            return "就在附近";
        } else if(m<=100){
            return "不足100米";
        } else if(m<=1000){
             int i_m= (int) m;
            return i_m+"米";
        }else{
          double chu_m=m/1000;
            DecimalFormat decimalFormat=new DecimalFormat("#.#");
            return decimalFormat.format(chu_m)+"km";
        }

    }

    //dp转px
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    //将px转换为dp
    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    //将大于一万浏览数进行文字转化
    public static String getSeecount(Integer seeCount){
            String countStr="";
              if(seeCount<10000){
                  countStr=seeCount+"浏览";
                  return countStr;
              }else {
                  DecimalFormat decimalFormat=new DecimalFormat("#.#");
                  countStr=decimalFormat.format(seeCount/10000)+"万浏览";
                 return countStr;
              }


    }
    //将大于一万进行万文字转化
    public static String getWancount(Integer count){
        String countStr="";
        if(count<10000){
            countStr=count+"";
            return countStr;
        }else {
            DecimalFormat decimalFormat=new DecimalFormat("#.#");
            countStr=decimalFormat.format(count/10000)+"万浏览";
            return countStr;
        }


    }


    //复制粘贴板
    public static boolean copyKeybroadContent(Context context,String content){
             try {
                 //获取剪贴板管理器：
                 ClipboardManager cm = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
                 ClipData mClipData = null;
                 mClipData = ClipData.newPlainText("content",content);
                 // 将ClipData内容放到系统剪贴板里。
                 assert cm != null;
                 cm.setPrimaryClip(mClipData);
                 return true;
             }catch (Exception e){
                 e.printStackTrace();
             return false;
             }

    }

    /**
     * 判断是否安装目标应用
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }


   //获取安装
    public Intent getInstallIntent(Context context,File file){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT>=24) {//判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(context, "com.stn.zjx.givingtreasure.fileprovider", file);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
            context.startActivity(install);
        } else{
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
            context.startActivity(install);
        }
        return intent;
    }


    /*
     * 毫秒转化时分秒毫秒
     */
    public static String formatTime(Long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;

        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        StringBuffer sb = new StringBuffer();
        if(day > 0) {
            sb.append(day+"");//天
        }
        if(hour > 0) {
            sb.append(hour+":");//小时
        }else{
            sb.append("00:");//小时
        }
        if(minute > 0) {
            sb.append(minute+":");//分
        }else{
            sb.append("00:");//分
        }
        if(second > 0) {
            sb.append(second+"");//秒
        }else{
            sb.append("00");//秒
        }
//        if(milliSecond > 0) {
//            sb.append(milliSecond+"");//豪秒
//        }
        return sb.toString();
    }

//     viewpager.setPageMargin(dip2px(this, 50) * -1);
//        viewpager.setPageTransformer(false, new ViewPager.PageTransformer() {
//        @Override
//        public void transformPage(View view, float position) {
//            if (view1 == view)
//                System.out.println("aaaaaa:" + view.toString() + "-" + position);
//            View imageView = view.findViewById(R.id.image);
//            //float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
//            if (position < -1 || position > 1) {
//                view.setScaleX(1);
//                view.setScaleY(1);
//                return;
//            }
//            float changeArea = 1 - MIN_SCALE;
//            position = Math.abs(position);
//            float scaleFactor = position * changeArea;
//            view.setScaleX(1 - scaleFactor);
//            view.setScaleY(1 - scaleFactor);
//
//        }
//
//    });


   //修改指示器
    public static void setIndicatorWidth(@NonNull final TabLayout tabLayout, final int margin) {
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    // 拿到tabLayout的slidingTabIndicator属性
                    Field slidingTabIndicatorField = tabLayout.getClass().getDeclaredField("slidingTabIndicator");
                    slidingTabIndicatorField.setAccessible(true);
                    LinearLayout mTabStrip = (LinearLayout) slidingTabIndicatorField.get(tabLayout);
                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);
                        //拿到tabView的mTextView属性
                        Field textViewField = tabView.getClass().getDeclaredField("textView");
                        textViewField.setAccessible(true);
                        TextView mTextView = (TextView) textViewField.get(tabView);
                        tabView.setPadding(0, 0, 0, 0);
                        // 因为想要的效果是字多宽线就多宽，所以测量mTextView的宽度
                        int width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }
                        // 设置tab左右间距,注意这里不能使用Padding,因为源码中线的宽度是根据tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = margin;
                        params.rightMargin = margin;
                        tabView.setLayoutParams(params);
                        tabView.invalidate();
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("slidingTabIndicator");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }


    }
    public  static void setAudioOpenClose(Context context,int index){
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

             audioManager.setStreamVolume(AudioManager.STREAM_MUSIC ,index,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE );


    }

}
